# coding:utf-8
# @Time    : 2021/12/10 8:54
# @Author  : Martin

"""
线下单品赠品
"""

from page_object.base import PageItems
from util.read_file import get_approve_data


class OnlineOrderGiftPage(PageItems):

    def __new__(cls, *args, **kwargs):
        instance = super().__new__(cls)
        instance._base_url = "/nspas-web-in/activityCreateFilter.do?activityType" \
                             f"=ORDERACTIVITY&activityChannel=2&comType={args[2]}&actRewardType=7"
        return instance

    def __init__(self, driver, logger, com_type):

        super().__init__(driver, logger)

    def input_act_rule(self, params):
        """
        输入赠品
        :param params:
        :return:
        """
        for param in params:
            index1 = params.index(param) + 1
            # 输入门槛金额
            self.input('css selector',
                       f'#detailinfoOrderPresentRule>table:nth-child({index1}) input[name="orderPresentRule.privilegeSill"]'
                       , param['limit'])
            self.select('css selector',
                        f'#detailinfoOrderPresentRule>table:nth-child({index1}) select[name="orderPresentRule.unit"]'
                        , param['limit_type'],'text')
            # 点击添加赠品
            self.click('css selector',
                       f'#detailinfoOrderPresentRule>table:nth-child({index1}) a[onclick="tradeScopeSet(this)"]')

            for item in param['gifts']:
                index2 = param['gifts'].index(item) + 1
                # 点击增加
                self.click('xpath', f'//a[@onclick="presentScopeAdd(\'{index1}\')"]')

                # 选择赠品类型
                self.select('css selector',
                            f'#detailinfoPresentScope{index1}>#detailedtablePresentScope:nth-child({index2}) select['
                            f'name="activityPresentScope.giftType"]', item['gift_type'])

                # 输入商品编码
                self.input('css selector',
                           f'#detailinfoPresentScope{index1}>#detailedtablePresentScope:nth-child({index2}) '
                           f'input[name="activityPresentScope.commodityCode"]', item['code'])

                # 输入单次赠送数量
                self.input('css selector',
                           f'#detailinfoPresentScope{index1}>#detailedtablePresentScope:nth-child({index2}) '
                           f'input[name="activityPresentScope.singleAmount"]', item['count'])

                # 输入赠送总数量
                self.input('css selector',
                           f'#detailinfoPresentScope{index1}>#detailedtablePresentScope:nth-child({index2}) '
                           f'input[name="activityPresentScope.totalAmount"]', item['total'])
                if item['gift_type'] == '1':
                    # 输入宣传价
                    self.input('css selector',
                               f'#detailinfoPresentScope{index1}>#detailedtablePresentScope:nth-child({index2}) '
                               f'input[name="activityPresentScope.balanceAmount"]', item['pub_price'])

            # 输入可选型号数量
            self.input('id', f'promotionGoods{index1}', param['option'])
            # self.js_input(f'#promotionGoods{index1}', param['option'], event='onblur')

            # 点击确定
            self.click('xpath', f'//a[@onclick="tradeScopeOk(\'{index1}\')"]')
            if index1 != len(params):
                # 点击增加层级
                self.click('xpath', '//a[@onclick="orderPresentAdd()"]')

    @staticmethod
    def get_approve_head_create():
        """
        获取总部新建审批流账号数据
        :return:
        """
        return get_approve_data('online_order_gift', 'head', 'create')

    def add_single(self, params):
        """
        添加单品包含
        :param params:商品范围列表
        :return:
        """
        self._select_relation('包含')
        for param in params:
            self._input_commdty_scope(**param)
            self.click('id', 'cmmdCodeAdd')
        self.click('link text', '添加到商品范围')

    def go_to_approve(self):
        """
        首次点击提交去审批
        :return:
        """
        self.click('id', 'submitBtn')

    def gift_remain_amount(self):
        return self.get_element_attr('id', 'remainAmount', 'value')

    @staticmethod
    def cal_lock_amount(total, price):
        return total * price

    def cal_all_lock_amount(self, act_info):
        i = 0
        rule_info = act_info['input_act_rule']
        lock_amount = 0
        while True:
            param = rule_info[i]
            for gift in param['gifts']:
                if gift['gift_type'] == '1':
                    total = gift['total']
                    price = gift['pub_price']
                    lock_amount += self.cal_lock_amount(total, price)
                else:
                    continue
            i += 1
            if i == len(rule_info):
                break
        self.logger.info(f"赠品预锁额度为<{lock_amount}>")
        return lock_amount


if __name__ == '__main__':
    js = '{"input_act_rule":[{"limit":10,"option":1,"gifts":[{"gift_type":1,"code":"000000000761203340","count":1,"total":2,"pub_price":1.11}]},{"limit":20,"option":1,"gifts":[{"gift_type":1,"code":"000000000104697611","count":1,"total":1,"pub_price":3.22}]}]}'

    # print(OnlineOrderGiftPage.cal_all_lock_amount(json.loads(js)))
    print(1.11*2)